package com.yimi.yinhepda.views.load_module

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.pda.uce.commom.util.BaseApplication
import com.pda.ym.base.BaseTitleActivity
import com.pda.ym.base.CommonViewHolder
import com.pda.ym.base.MultiTypeSupport
import com.pda.ym.callbacks.UICallBack
import com.pda.ym.entity.bean.CarPlanTaskEntity
import com.pda.ym.net.NetRequest
import com.pda.ym.utils.*
import com.uce.pda.util.MediaPlayerUtil
import com.yimi.yinhepda.R
import com.yimi.yinhepda.adapter.RecycleAdapter.NewLoadTaskAdapter
import com.yimi.yinhepda.db.dao.DepartmentTableDao
import com.yimi.yinhepda.entity.bean.BaseDictEntity
import com.yimi.yinhepda.entity.bean.CheckBoxItemEntity
import com.yimi.yinhepda.entity.request.QueryCarPlanTaskRequest
import com.yimi.yinhepda.entity.response.CarPlanTaskResponse
import com.yimi.yinhepda.entity.response.QueryBaseDictResponse
import com.yimi.yinhepda.event.CreateStowagesEvent
import com.yimi.yinhepda.utils.Common
import com.yimi.yinhepda.utils.ToastUtil
import com.yimi.yinhepda.views.createPackage_module.CreateDeptSelectActivity
import kotlinx.android.synthetic.main.activity_new_load_task.*
import kotlinx.android.synthetic.main.select_car_plate.*
import kotlinx.android.synthetic.main.view_search_laod_task.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

/**
 * @author: lj
 * Date: 2020/4/10 13:53
 * Description:装车任务列表
 */
class NewLoadTaskActivity : BaseTitleActivity(true), CommonViewHolder.onItemCommonClickListener {

    private var mTaskList = mutableListOf<CarPlanTaskEntity>()
    private var mAdapter: NewLoadTaskAdapter? = null
    private var mTaskEntity: CarPlanTaskEntity? = null
    //合并装卸车
    private var mDictCombind: MutableList<BaseDictEntity>? = null
    /**
     * 下一站待选择集合
     */
    private var mNextDeptList = mutableListOf<CheckBoxItemEntity>()
    /**
     * 已选择的下一站集合
     */
    private var mSelectedNextDeptList = mutableListOf<CheckBoxItemEntity>()
    private var mSelectPlanTaskPosition: Int = -1
    //创建的支线任务号集合
    private var mCreateStowageNos = mutableListOf<String>()
    //支持多种item
    private val mMltiTypeSupport = MultiTypeSupport<CarPlanTaskEntity> { carPlanTaskEntity: CarPlanTaskEntity, i: Int ->
        when (i) {
            0 -> R.layout.view_search_laod_task
            else -> R.layout.adapter_new_load_task_item
        }
    }

    override fun getPageName(): String {
        return "装车任务列表"
    }

    override fun setContentViewId(): Int {
        return R.layout.activity_new_load_task
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        MediaPlayerUtil.setValue(BaseApplication.getContext(), 100)
        btn_back.setOnClickListener(this)
        btn_create_branch_task.setOnClickListener(this)
        btn_exec.setOnClickListener(this)

        if (!EventBus.getDefault().isRegistered(this)) {
            //注册事件
            EventBus.getDefault().register(this)
        }

        //数据字典：查询合并装卸车开关
        queryDictCombindLoadUnload()
        //数据字典，查询融合装车扫描创建任务开关
        Common.queryMergeLoadScanCreateTask()

        //默认添加第一项为搜索条件
        mTaskList.add(CarPlanTaskEntity())
        loadUIAdapter()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v?.id) {
            R.id.btn_back -> finish()
            R.id.btn_carPlate -> {
                //省市车牌
                CarNoSelectDialog.showCarPlateDialog(this) { carPlate ->
                    btn_carPlate.text = carPlate
                }
            }
            R.id.btn_selectNextDept -> {
                //选择下一站
                val intent = Intent(this, CreateDeptSelectActivity::class.java)
                intent.putExtra("currentDept", sharedPreferUtil.deptCode)
                intent.putExtra("inputType", 1)
                startActivityForResult(intent, 0)
            }
            R.id.btn_down -> {
                //搜索
                val carPlate = et_carNo.text.toString()
                if (StringUtils.isEmpty(carPlate) && StringUtils.isEmpty(btn_selectNextDept.text.toString())) {
                    showToast("请输入车牌号或下一站！")
                    SoundVibratorManager.playSound(2)
                    return
                }
                var nextDeptCode = if (btn_selectNextDept.tag == null) {
                    null
                } else {
                    btn_selectNextDept.tag.toString()
                }
                //隐藏键盘
                hideSoftInput()
                if (carPlate.isNotEmpty()) {
                    nextDeptCode = null
                    btn_selectNextDept.tag = "";
                    btn_selectNextDept.text = "";
                }
                //查询发车计划
                queryCarPlanTask(btn_carPlate.text.toString() + carPlate.toUpperCase(), nextDeptCode, null)
            }
            R.id.btn_create_branch_task -> {
                //创建支线任务
                val intent = Intent(this, CreateBranchTaskActivity::class.java)
                intent.putExtra(CreateBranchTaskActivity.LOAD_KEY, CreateBranchTaskActivity.LOAD_TYPE)
                startActivity(intent)
            }
            R.id.btn_exec -> {
                //执行
                if (mTaskList.isNullOrEmpty()) {
                    showToast("请先搜索装车任务！")
                    SoundVibratorManager.playSound(2)
                    return
                }

                val checkList = mutableListOf<CarPlanTaskEntity>()
                mTaskList.forEach { task ->
                    if (task.isCheck) {
                        checkList.add(task)
                    }
                }

                if (checkList.isNullOrEmpty()) {
                    showToast("请选择一项任务执行！")
                    SoundVibratorManager.playSound(2)
                    return
                }

                val deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE)
                if (deptType == 5 || deptType == 6) {
                    //判断是否是分拨,跳转至装卸组
                    LoadUtil.toClassActivity(this, null, checkList, LoadUnloadGroupActivity::class.java, 1)
                } else {
                    //获取发车计划下一站.显示，选择下一站，创建装车任务
                    LoadUtil.showNextDeptDialog(this, checkList, 1)
                }
            }
        }
    }

    /**
     * 隐藏软键盘
     */
    private fun hideSoftInput() {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager;
        //imm.showSoftInput(view,InputMethodManager.SHOW_FORCED);
        imm.hideSoftInputFromWindow(et_carNo.windowToken, 0); //强制隐藏键盘
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == 0) {
            btn_selectNextDept.text = data!!.getStringExtra("deptName")
            btn_selectNextDept.tag = data.getStringExtra("deptCode")
        }
    }

    override fun handleBarCode(result: String?) {
        if (result == null) {
            SoundVibratorManager.playSound(2)
            showToast("运单号扫描失败")
        } else {
            val palletName = StringUtils.getPalletName(result)
            if (palletName != "") {
                btn_carPlate.text = palletName
                val carNo = result.substring(3)
                et_carNo.setText(carNo)
                queryCarPlanTask(palletName + carNo, null, null)
            } else {
                queryCarPlanTask(null, null, result)
            }
        }
    }

    /**
     * 查询发车计划
     */
    private fun queryCarPlanTask(carNo: String?, destDeptCode: String?, taskNo: String?) {
        val request = QueryCarPlanTaskRequest()
        destDeptCode?.let {
            request.destDeptCode = it
        }
        request.srcDeptCode = sharedPreferUtil.deptCode
        carNo?.let {
            if (it.length > 1) {
                request.carNo = it
            }
        }
        taskNo?.let {
            if (it.startsWith("H")||it.startsWith("J")) {
                request.taskNo = it
            } else {
                request.stowageNo = it
            }

        }
        showPgDlg("查询中...")
        NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setUrl(Constants.URL_V2_QUERY_CAR_PLAN_TASK)
                .setRequestObject(request)
                .setResponsClazz(CarPlanTaskResponse::class.java)
                .execute(object : UICallBack() {
                    override fun onError(msg: String) {
                        dismissPgDlg()
                        showToast(msg)
                        SoundVibratorManager.playSound(2)
                    }

                    override fun onSuccess(obj: Any) {
                        dismissPgDlg()
                        val response = obj as CarPlanTaskResponse
                        if (!response.data.isNullOrEmpty()) {

                            mTaskList.forEach { task ->
                                task.isCheck = false
                            }

                            val tasks = response.data
                            val departDao = DepartmentTableDao()
                            for ((index, planTask) in tasks.withIndex()) {
                                if (planTask.taskNo.startsWith("P")) {
                                    planTask.loadTasks?.forEach { loadTask ->
                                        //查询跨越虚拟网点
                                        val departmentTable = departDao.getDataByDeptType(loadTask.destDeptCode, "7")
                                        if (departmentTable != null) {
                                            //设置为跨越任务类型
                                            planTask.taskType = 1
                                        }
                                    }
                                }
                                mCreateStowageNos.forEach { stowageNo ->
                                    planTask.loadTasks?.forEach { loadTask ->
                                        if (stowageNo == loadTask.stowageNo) {
                                            planTask.isCheck = true
                                            mSelectPlanTaskPosition = index
                                        }
                                    }
                                }
                            }
                            tasks.forEach { queryTask ->
                                mTaskList.listIterator().run {
                                    var hasTask = false
                                    while (this.hasNext()) {
                                        val planTask = this.next()
                                        if (planTask.taskNo == queryTask.taskNo) {
                                            hasTask = true
                                        }
                                    }
                                    if (!hasTask) {
                                        this.add(queryTask)
                                    }
                                }
                            }

                            loadUIAdapter()
                            if (mSelectPlanTaskPosition >= 0) {
                                rv_load_task_list.scrollToPosition(mSelectPlanTaskPosition + 1)
                            }
                            SoundVibratorManager.playSound(1)
                        } else {
                            showToast("未查询到相关任务！")
                            SoundVibratorManager.playSound(2)
                        }
                    }
                })
    }

    private fun loadUIAdapter() {
        if (mAdapter == null) {
            mAdapter = NewLoadTaskAdapter(this, mTaskList, this, mMltiTypeSupport, this)
            rv_load_task_list.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
            rv_load_task_list.adapter = mAdapter
        } else {
            mAdapter!!.notifyDataSetChanged()
        }
    }

    /**
     * 查询数据字典：合并装卸车（combind_load_unload）
     */
    private fun queryDictCombindLoadUnload() {
        showPgDlg("正在加载配置...")
        val params: MutableMap<String, String> = HashMap(2)
        params["dictCode"] = "combind_load_unload"
        //查询类型，1-只查询未作废的，为null则查询所有(包含作废和未作废的)
        params["type"] = "1"
        NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryBaseDictResponse::class.java)
                .setUrl(Constants.URL_QUERY_DICT)
                .setParams(params)
                .setConnTimeOut(10 * 1000.toLong())
                .execute(object : UICallBack() {
                    override fun onError(msg: String) {
                        dismissPgDlg()
                        showToast(msg)
                    }

                    override fun onSuccess(obj: Any) {
                        dismissPgDlg()
                        val response = obj as QueryBaseDictResponse
                        if (response.data != null) {
                            mDictCombind = response.data
                        }
                    }
                })
    }

    override fun showBack(): Boolean {
        return false
    }

    override fun setBack() {
        finish()
    }

    override fun setTitle(): String {
        return pageName
    }

    override fun onItemClickListener(position: Int) {
        mTaskEntity = mTaskList[position]
        if (mTaskEntity!!.isCheck) {
            mTaskEntity!!.isCheck = false
        } else {
            //已选择计数
            var checkCount = 0
            //已选择任务集合
            val checkTaskList = mutableListOf<CarPlanTaskEntity>()
            mTaskList.forEach { task ->
                if (task.isCheck) {
                    checkCount++
                    checkTaskList.add(task)
                }
            }

            //是否配置数据字典合并装车的部门
            var isComBind = false
            val currentDeptCode = SharedPreferUtil.getInstance().deptCode
            if (mDictCombind != null) {
                for (item in mDictCombind!!) {
                    //合并装车部门
                    val deptCode = item.dictValue
                    //合并装车开关
                    val param1 = item.externalParam1
                    if (currentDeptCode == deptCode && "1" == param1) {
                        isComBind = true
                        break
                    }
                }
            }

            if (checkCount > 10) {
                ToastUtil.showToast("最多选择十个任务！")
                SoundVibratorManager.playSound(2)
                return
            }

            if (!isComBind) {
                if (checkTaskList.isNotEmpty()) {
                    //是否为相同车牌号
                    var sameCarNo = false
                    checkTaskList.forEach { task ->
                        if (mTaskEntity!!.vehNo == task.vehNo) {
                            sameCarNo = true
                            return@forEach
                        }
                    }
                    if (!sameCarNo) {
                        ToastUtil.showToast("不可选择不同车牌号的任务！")
                        SoundVibratorManager.playSound(2)
                        return
                    }
                }

                //限制干线车线任务只能选择一个
                if (mTaskEntity!!.taskNo != null) {
                    if (mTaskEntity!!.beTask == 1 && checkTaskList.isNotEmpty()) {
                        //当前选择的是车线任务，且已有其他任务，不能合并装车
                        ToastUtil.showToast("车线任务不能合并装车！")
                        SoundVibratorManager.playSound(2)
                        return
                    } else {
                        //当前选择的是其他任务，且已有车线任务，不支持合并装车
                        checkTaskList.forEach { task ->
                            if (task.beTask == 1) {
                                ToastUtil.showToast("车线任务不能合并装车！")
                                SoundVibratorManager.playSound(2)
                                return
                            }
                        }
                    }
                }
            }

            if (mTaskEntity!!.taskType == 1 && checkTaskList.isNotEmpty()) {
                //当前选择的是同行任务，且有其他任务已选择
                ToastUtil.showToast("同行任务不支持合并装车！")
                SoundVibratorManager.playSound(2)
                return
            } else {
                //当前选择的是其他任务，且有同行任务已选择
                checkTaskList.forEach { task ->
                    if (task.taskType == 1) {
                        ToastUtil.showToast("同行任务不支持合并装车！")
                        SoundVibratorManager.playSound(2)
                        return
                    }
                }
            }

            mTaskEntity!!.isCheck = true
        }
        mAdapter?.notifyItemChanged(position)
    }

    override fun onItemLongClickListener(position: Int) {
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMainEventBus(createEvent: CreateStowagesEvent) {
        if (createEvent.fromActivity == 1) {
            mTaskList.clear()
            mTaskList.add(CarPlanTaskEntity())
            loadUIAdapter()
            //点击搜索
            btn_down.performClick()
        } else {
            mCreateStowageNos = createEvent.stowageNos!!
            btn_carPlate.text = createEvent.carNo?.substring(0, 1)
            et_carNo.setText(createEvent.carNo?.substring(1))
            if (createEvent.nextDeptCode != null) {
                btn_selectNextDept.tag = createEvent.nextDeptCode
                btn_selectNextDept.text = createEvent.nextDeptCodeName
            }
            //点击搜索
            btn_down.performClick()
        }

    }

}